//
//  UIUtils.m
//  旅拍1.0
//
//  Created by 司马帅帅 on 15/7/6.
//  Copyright (c) 2015年 司马帅帅. All rights reserved.
//

#import "UIUtils.h"

@implementation UIUtils

//根据宽度求高度  content 计算的内容  width 计算的宽度 font字体大小
+ (CGFloat)getHeightWithContent:(NSString *)content width:(CGFloat)width font:(CGFloat)font{
    if(!content){
        return 0;
    }
    CGRect rect = [content boundingRectWithSize:CGSizeMake(width, 999)
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                        context:nil];
    return rect.size.height;
}

//根据高度度求宽度  content 计算的内容  Height 计算的高度 font字体大小
+ (CGFloat)getWidthWithContent:(NSString *)content height:(CGFloat)height font:(CGFloat)font{
    if (!content) {
        return 0;
    }
    
    CGRect rect = [content boundingRectWithSize:CGSizeMake(999, height)
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                        context:nil];
    return rect.size.width;
}

//判断一个字符串是否为空
+ (BOOL)isBlankString:(NSString *)string
{
    if (!string) {
        return YES;
    }
    if (string.length == 0) {
        return YES;
    }
    if (string == nil) {
        return YES;
    }
    if ([string isEqual:[NSNull null]]) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([string isEqualToString:@"(null)"]) {
        return YES;
    }
    if ([string isEqualToString:@"<null>"]) {
        return YES;
    }
    return NO;
}
// 判断数组是否为空
+ (BOOL)isBlankArray:(NSArray *)array
{
    if (array != nil && ![array isKindOfClass:[NSNull class]] && array.count != 0)
    {
        return YES;
    }
    return NO;
}

+ (int)isRoleIdentity
{
    // 1 投资经理 ；2 高管(董事长 CEO 合伙人)；3 其他(人事 财务 法务)
    if ([ROLECODE isEqualToString:@"TZJL"]) {
        return 1;
    }
    if ([ROLECODE isEqualToString:@"DSZ"])
    {
        return 2;
    }
    if ([ROLECODE isEqualToString:@"CEO"] )
    {
        return 2;
    }
    if ([ROLECODE isEqualToString:@"HHR"])
    {
        return 2;
    }
    return 3;
}





+(void)setAlerView
{
    UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"二期开发中，敬请期待！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alerView show];

}
+(void)setAlerViewOne
{
    UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"你没有权限" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alerView show];
    
    
}
// 获得当前日期的上个月的日期
+ (NSString *)getBeformouthData
{
    NSString *_beforStartMouth;
    NSString *_beforEndMouth;
    NSString *dataStr;
    
    
    NSInteger year,month,day;
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    
    
    comps = [calendar components:unitFlags fromDate:now];
    year = [comps year];
    month = [comps month];
    day = [comps day];
    
    
//    now = [NSString stringWithFormat:@"%ld-%ld-%ld",(long)year,(long)month,(long)day];
    //   month获取现在的月份，然后 判断是上个月份是否为12月
    if (month!=1) {
        //       如果mouth!=1,那么上个月月初为1号，年份不变
        _beforStartMouth = [NSString stringWithFormat:@"%ld-%ld-01",(long)year,month-1];
        //        处理上个月份为2月的特殊情况，
        if (month!=3) {
            //            如果上个月的月份为 4  6  9  11 月份，他们月末是30号
            if (month == 5 || month==7 || month ==10 || month ==12) {
                _beforEndMouth = [NSString stringWithFormat:@"%ld-%ld-30",(long)year,month-1];
            }
            else {
                _beforEndMouth = [NSString stringWithFormat:@"%ld-%ld-31",(long)year,month-1];
                
            }
        }
        //        如果本月是3月份，上个月为为2月份，闰年2月月末29天，非闰年28天
        else {
            if ((year%4==0 && year%100!=0) || year%400==0) {
                _beforEndMouth = [NSString stringWithFormat:@"%ld-%ld-29",(long)year,month-1];
                
            }
            else {
                _beforEndMouth = [NSString stringWithFormat:@"%ld-%ld-28",(long)year,month-1];
                
            }
        }
        
    }
    //    如果当前月份是1月，上个月份就是12月  year-1,month=12
    else {
        _beforStartMouth = [NSString stringWithFormat:@"%ld-12-1",year-1];
        
        _beforEndMouth = [NSString stringWithFormat:@"%ld-12-31",year-1];
        
    }
    dataStr = [NSString stringWithFormat:@"%@%@",_beforStartMouth,_beforEndMouth];
    return dataStr;
    
}

// 获得本周开始结束日期
+ (NSString *)getWeekBeginAndEndData{
    
    NSDate *newDate = [NSDate date];
    
    double interval = 0;
    NSDate *beginDate = nil;
    NSDate *endDate = nil;
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:2];//设定周一为周首日
    BOOL ok = [calendar rangeOfUnit:NSWeekCalendarUnit startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *beginString = [myDateFormatter stringFromDate:beginDate];
    NSString *endString = [myDateFormatter stringFromDate:endDate];
    
    NSString *sd = [NSString stringWithFormat:@"%@%@",beginString,endString];
    
    return sd;
}
// 获得本月开始结束日期
+ (NSString *)getMonthBeginAndEndData{
    NSDate *newDate = [NSDate date];
    double interval = 0;
    NSDate *beginDate = nil;
    NSDate *endDate = nil;
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:2];//设定周一为周首日
    BOOL ok = [calendar rangeOfUnit:NSMonthCalendarUnit startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *beginString = [myDateFormatter stringFromDate:beginDate];
    NSString *endString = [myDateFormatter stringFromDate:endDate];
    
    NSString *sd = [NSString stringWithFormat:@"%@%@",beginString,endString];
    return sd;
}





//把状态栏设置为白色
+ (void)setStatusBarColor
{
//    //设置状态栏为白色
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

/**
 * 颜色变图片
 */
+ (UIImage *)imageFromColor:(UIColor *)color forSize:(CGSize)size withCornerRadius:(CGFloat)radius {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Begin a new image that will be the new image with the rounded corners
    // (here with the size of an UIImageView)
    UIGraphicsBeginImageContext(size);
    
    // Add a clip before drawing anything, in the shape of an rounded rect
    [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius] addClip];
    // Draw your image
    [image drawInRect:rect];
    
    // Get the image, here setting the UIImageView image
    image = UIGraphicsGetImageFromCurrentImageContext();
    
    // Lets forget about that we were drawing
    UIGraphicsEndImageContext();
    return image;
}

/**
 * 去掉首末空格 空行
 */
+ (NSString *)stringCharacterSet:(NSString *)inputString{
    
    NSString *temp = [inputString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return temp;
}

+ (NSString *)stringTrim:(NSString *)inputString{
    NSString *str = [inputString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return str;
}

// 获得系统的时间 ，并转化为中国时区的时间
+ (NSString *)dateStringWithDate:(NSDate *)date DateFormat:(NSString *)dateFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    NSString *str = [dateFormatter stringFromDate:date];
    return str ? str : @"";
}

+ (NSString *)dateStringWithDateStr:(NSString *)dateStr DateFormat:(NSString *)dateFormat
{
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dateStr doubleValue] / 1000];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    NSString *str = [dateFormatter stringFromDate:date];
    return str ? str : @"";
    
}

//   美国时间转化为现在的时间
+ (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate
{
    //设置源日期时区
    NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    //设置转换后的目标日期时区
    NSTimeZone *destinationTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate *destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate] ;
    return destinationDateNow;
}

+ (NSString *)getDataStringFromTimestamp:(NSString *)string
{
    // 转换为2015-11-11 13：00
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[string doubleValue] / 1000];
    // 时间添加八个小时
    
    //设置源日期时区
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    //设置转换后的目标日期时区
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:date];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:date];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:date] ;

    NSString *time = [NSString stringWithFormat:@"%@",destinationDateNow];
    
    return time;

}

#pragma mark - 传入float和要保留小数点后的位数，返回string类型

+(NSString *)notRounding:(double)price afterPoint:(int)position{
    
    int decimalNum = position; //保留的小数位数
    
    double doubleNumber = 1.230;
    
    NSNumberFormatter *nFormat = [[NSNumberFormatter alloc] init];
    
    [nFormat setNumberStyle:NSNumberFormatterDecimalStyle];
    
    [nFormat setMaximumFractionDigits:decimalNum];
    
    

    return [NSString stringWithFormat:@"dddd"];
    
}


// 当没有网络的时候 展示的视图
+  (UIView *)noNetworkViewwithFrame:(CGRect )frame
{
    
    UIView *  _noNworkView = [[UIView alloc]initWithFrame:frame];
    _noNworkView.backgroundColor = AllViewBackgroundColor;
    
    UIImageView *imageVi = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth-100)/2, (_noNworkView.height-145)/2, 100, 100)];
    imageVi.contentMode = UIViewContentModeScaleAspectFit;
    [imageVi setImage:[UIImage imageNamed:@"network"]];
    [_noNworkView addSubview:imageVi];
    
    UILabel * lableOne = [[UILabel alloc]initWithFrame:CGRectMake(0, imageVi.bottom+10, ScreenWidth, 20)];
    lableOne.text = @"网络连接失败";
    lableOne.textAlignment = NSTextAlignmentCenter;
    lableOne.textColor = [UIColor colorWithHexString:@"#aaa"];
    lableOne.font =[UIFont systemFontOfSize:15.0];
    [_noNworkView addSubview:lableOne];
    
    UILabel * lableTwo = [[UILabel alloc]initWithFrame:CGRectMake(0, lableOne.bottom+10, ScreenWidth, 20)];
    lableTwo.text = @"请检查网络或者下拉刷新";
    lableTwo.textAlignment = NSTextAlignmentCenter;
    lableTwo.textColor = [UIColor colorWithHexString:@"#aaa"];
    lableTwo.font =[UIFont systemFontOfSize:15.0];
    [_noNworkView addSubview:lableTwo];
    
    return _noNworkView;
}

// 当没有数据的时候 展示的视图
+ (UIView *)noDataView:(NSString *)string withFrame:(CGRect )frame
{
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = AllViewBackgroundColor;
    view.layer.cornerRadius = 2;
    view.layer.masksToBounds= YES;
    
    UIImageView *imageVi = [[UIImageView alloc]initWithFrame:CGRectMake((view.width-100)/2, (view.height-145)/2, 100, 100)];
    imageVi.contentMode = UIViewContentModeCenter;
    [imageVi setImage:[UIImage imageNamed:@"zanwu"]];
    [view addSubview:imageVi];
    

    UILabel * lableOne = [[UILabel alloc]initWithFrame:CGRectMake(0, imageVi.bottom+5, view.width, 20)];
    lableOne.text = [NSString stringWithFormat:@"%@暂无数据",string];
    lableOne.textAlignment = NSTextAlignmentCenter;
    lableOne.textColor = [UIColor colorWithHexString:@"#aaa"];
    lableOne.font =[UIFont systemFontOfSize:13.0];
    [view addSubview:lableOne];
    view.hidden = YES;
    
    return view;
    
    
}

/**
 * 和当前时间的比较
 * @parma selectDate:选择的日期
 * @return 1:大于当前日期 -1:小于当前时间 0:等于当前时间
 */
+ (int)compareDateWithSelectDate:(NSString *)selectDate
{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *fomatter = [[NSDateFormatter alloc] init];
    [fomatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *curentDateStr = [fomatter stringFromDate:currentDate];
    currentDate = [fomatter dateFromString:curentDateStr];
    
    int result = [[fomatter dateFromString:selectDate] compare:currentDate];
    if(result == NSOrderedDescending)
    {
        return 1;
    }
    else if(result == NSOrderedAscending)
    {
        return -1;
    }
    return 0;
}
+ (NSString *)accordingToFileSuffix:(NSString *)string
{
    
    string = [string lowercaseString];
     if([string isEqualToString:@"doc"]||[string isEqualToString:@"docx"]){

        return @"word";

    }else if([string isEqualToString:@"xls"]||[string isEqualToString:@"xlsx"]){

        return @"excel";

    }
    else if([string isEqualToString:@"ppt"]||[string isEqualToString:@"pptx"]){
        
        return @"ppt";
        
    }else if([string isEqualToString:@"pdf"]){

        return @"pdf";

    }
    else
    {
        return @"wufile";
    }


}

+ (NSMutableAttributedString *)getAttributedStringWithLeftStr:(NSString *)leftStr withleftFont:(CGFloat )leftFont withLeftColor:(UIColor *)leftColor withRightStr:(NSString *)rightStr withRightFont:(CGFloat )rightFont withRightColor:(UIColor *)rightColor
{

    NSString *divisionStr = leftStr;
    NSString *topStr = rightStr;
    NSString *sectionTitleStr = [NSString stringWithFormat:@"%@ %@",divisionStr,topStr];
    NSMutableAttributedString *infoStr = [[NSMutableAttributedString alloc]initWithString:sectionTitleStr];
    NSRange range = [sectionTitleStr rangeOfString:divisionStr];
    [infoStr setAttributes:@{
                             NSFontAttributeName:[UIFont systemFontOfSize:leftFont],
                             NSForegroundColorAttributeName:leftColor
                             } range:range];
    
    NSRange range1 = [sectionTitleStr rangeOfString:topStr];
    [infoStr setAttributes:@{
                             NSFontAttributeName:[UIFont systemFontOfSize:rightFont],
                             NSForegroundColorAttributeName:rightColor
                             } range:range1];

    return infoStr;
    

}



@end
